<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span><i class="el-icon-user"></i> 医生站 - 住院患者名单</span>
      </div>
    </template>

<!--    <el-form :inline="true" :model="searchForm" @submit.prevent="handleSearch">-->
<!--      <el-form-item label="病人姓名">-->
<!--        <el-input v-model="searchForm.patientName" placeholder="输入病人姓名"></el-input>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="病床号">-->
<!--        <el-input v-model="searchForm.bedNo" placeholder="输入病床号"></el-input>-->
<!--      </el-form-item>-->
<!--      <el-form-item>-->
<!--        <el-button type="primary" @click="handleSearch">查询</el-button>-->
<!--        <el-button @click="handleReset">重置</el-button>-->
<!--      </el-form-item>-->
<!--    </el-form>-->

    <el-table :data="tableData" v-loading="loading" style="width: 100%">
      <el-table-column prop="patientName" label="病人姓名" width="100" />
      <el-table-column prop="age" label="年龄" width="80" />
      <el-table-column prop="gender" label="性别" width="60">
        <template #default="scope">
          <div v-if="scope.row.gender === 1">{{"男"}}</div>
          <div v-else-if="scope.row.gender === 2">{{"女"}}</div>
          <div v-else>{{"未知"}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="120" />
      <el-table-column prop="roomName" label="科室" width="150" />
      <el-table-column prop="wardNo" label="病房号" width="100" />
      <el-table-column prop="bedNo" label="病床号" width="100" />
      <el-table-column prop="doctorName" label="主治医生" width="120" />
      <el-table-column prop="oaDate" label="入院时间" width="180" />
      <el-table-column label="操作" fixed="right" width="120">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleDiagnose(scope.row)">
            就诊
          </el-button>
        </template>
      </el-table-column>
    </el-table>

<!--    <el-pagination-->
<!--        style="margin-top: 20px;"-->
<!--        v-model:current-page="pagination.pageNum"-->
<!--        v-model:page-size="pagination.pageSize"-->
<!--        :page-sizes="[10, 20, 50, 100]"-->
<!--        layout="total, sizes, prev, pager, next, jumper"-->
<!--        :total="pagination.total"-->
<!--        @size-change="handleSizeChange"-->
<!--        @current-change="handlePageChange"-->
<!--    />-->
  </el-card>

  <el-dialog
      v-model="diagnoseDialogVisible"
      :title="'病人工作站 - ' + currentPatient.patientName + ' (' + currentPatient.bedNo + ')'"
      width="80%"
      @close="handleModalClose"
  >
    <el-tabs v-model="activeTab" type="border-card">

      <el-tab-pane label="编写医嘱" name="writeOrder">
        <el-input
            v-model="newOrderContent"
            type="textarea"
            :rows="5"
            placeholder="请输入医嘱内容..."
        ></el-input>
        <el-button type="primary" @click="submitNewOrder" style="margin-top: 15px;">提交医嘱</el-button>
        <el-divider />
        <span style="font-weight: bold;">历史医嘱</span>
        <el-table :data="patientOrders" max-height="300">
          <el-table-column prop="content" label="医嘱内容" />
          <el-table-column prop="doctorName" label="开立医生" width="120" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 0 ? 'warning' : 'success'">
                {{ scope.row.status === 0 ? '待执行' : '已执行' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="nurseName" label="执行护士" width="120" />
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="病例编写" name="writeCase">
        <el-alert title="住院部医生编写病例状态为1 " type="info" show-icon :closable="false" />
        <el-input
            v-model="caseFileContent"
            type="textarea"
            :rows="20"
            placeholder="请在此处编写病人病例..."
            style="margin-top: 15px;"
        ></el-input>
        <el-button type="primary" @click="submitCaseFile" style="margin-top: 15px;">保存病例</el-button>
      </el-tab-pane>

      <el-tab-pane label="出院申请" name="applyDischarge">
        <div style="padding: 20px;">
          <p>病人姓名: <strong>{{ currentPatient.patientName }}</strong></p>
          <p>入院时间: <strong>{{ currentPatient.admissionDate }}</strong></p>
          <p>当前诊断: <strong>{{ currentPatient.diagnosis }}</strong></p>
          <el-alert title="点击确定按钮，数据库表生成出院申请单，状态为申请中 0 " type="info" show-icon :closable="false" style="margin-top: 20px;"/>
          <el-button type="danger" @click="submitDischargeApplication" style="margin-top: 20px;">
            确认提交出院申请
          </el-button>
        </div>
      </el-tab-pane>

      <el-tab-pane label="开检查" name="openExam">
        <p>住院部开检查，选择检查项目，点击提交。 </p>
      </el-tab-pane>

      <el-tab-pane label="开药" name="prescribe">
        <p>住院部开药，选择药品，点击提交，药品库存会修改。 </p>
      </el-tab-pane>

      <el-tab-pane label="手术申请" name="applySurgery" v-loading="surgeryTabLoading">
        <el-alert title="住院部开手术申请状态为 0 ：申请中" type="info" show-icon :closable="false" />

        <el-form :model="surgeryForm" :rules="surgeryRules" ref="surgeryFormRef" label-width="100px" style="margin-top: 20px; width: 80%;">
          <el-form-item label="手术项目" prop="surgeryItemId">
            <el-select
                v-model="surgeryForm.surgeryItemId"
                placeholder="请选择手术项目 (可搜索)"
                filterable
                style="width: 100%;"
            >
              <el-option
                  v-for="item in allSurgeryItems"
                  :key="item.id"
                  :label="`${item.item_name} (¥${item.price})`"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="手术时间" prop="surgeryTime">
            <el-date-picker
                v-model="surgeryForm.surgeryTime"
                type="datetime"
                placeholder="选择手术日期和时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%;"
                :disabled-date="disablePastDates"
                :disabled-hours="disablePastHours"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitSurgeryApplication">提交申请</el-button>
          </el-form-item>
        </el-form>

        <el-divider />

        <span style="font-weight: bold;">该患者的手术申请记录</span>
        <el-table :data="patientSurgeries" max-height="250">
          <el-table-column prop="surgeryName" label="手术项目" />
          <el-table-column prop="surgeryTime" label="拟定手术时间" width="200" />
          <el-table-column prop="status" label="状态" width="120">
            <template #default="scope">
              <el-tag :type="scope.row.status === 0 ? 'warning' : 'success'">
                {{ formatSurgeryStatus(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="退药申请" name="returnMedicine">
        <p>住院部退药申请，查询患者未用完的药品，选择后点击提交。 </p>
      </el-tab-pane>

    </el-tabs>
  </el-dialog>

</template>

<script>
// 引入 Element Plus 的消息提示和确认框
import { ElMessage, ElMessageBox } from 'element-plus';
import {queryAll} from "../api/inpatient.js";
import {queryByPatientId} from "../api/doctorOrder.js";

// --- 模拟API调用 ---
// --- *** 6. 新增的手术模拟API *** ---

// 模拟API: 获取所有手术项目 (来自 surgery_item)
const fetchAllSurgeryItemsApi = () => {
  console.log("获取所有可用的手术项目...");
  return new Promise(resolve => {
    setTimeout(() => {
      resolve([
        { id: 1, item_name: '阑尾切除术', price: 5000.00 },
        { id: 2, item_name: '膝关节镜手术', price: 12000.00 },
        { id: 3, item_name: '剖宫产术', price: 8000.00 },
        { id: 4, item_name: '冠状动脉搭桥术', price: 80000.00 },
      ]);
    }, 300);
  });
};

// 模拟API: 获取指定病人的手术申请记录 (来自 med_surgery_application)
const fetchPatientSurgeriesApi = (patientId) => {
  console.log(`获取病人ID ${patientId} 的手术申请记录...`);
  return new Promise(resolve => {
    setTimeout(() => {
      // 模拟病人3(刘强)已有一条申请
      if (patientId === 3) {
        resolve([
          { id: 1, surgeryName: '膝关节镜手术', surgeryTime: '2025-10-31 09:00:00', status: 0 }
        ]);
      } else {
        resolve([]);
      }
    }, 300);
  });
};

// 模拟提交新医嘱
const submitOrderApi = (patientId, content) => {
  console.log("提交医嘱:", patientId, content);
  return new Promise(resolve => setTimeout(resolve, 500));
};

// 模拟保存病例
const submitCaseFileApi = (patientId, content) => {
  console.log("保存病例:", patientId, content);
  return new Promise(resolve => setTimeout(resolve, 500));
};

// 模拟提交出院申请
const submitDischargeApi = (patientId) => {
  console.log("提交出院申请:", patientId);
  return new Promise(resolve => setTimeout(resolve, 500));
};

// 模拟API: 提交新的手术申请
const submitSurgeryApi = (request) => {
  console.log("提交手术申请:", request);
  // request 结构: { patientId, surgeryItemId, surgeryTime, doctorId }
  return new Promise(resolve => {
    setTimeout(() => {
      // 模拟返回新创建的申请记录
      resolve({
        id: Math.floor(Math.random() * 1000),
        surgeryName: '阑尾切除术', // (模拟)
        surgeryTime: request.surgeryTime,
        status: 0 // 申请中
      });
    }, 500);
  });
};

// --- Vue 组件定义 ---
export default {
  name: "InpatientDoctorStation",
  // 1. data() 选项
  data() {
    return {
      // 搜索表单
      searchForm: {
        patientName: '',
        bedNo: ''
      },
      // 表格数据
      tableData: [],
      loading: false,
      // 分页
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },

      // --- 就诊弹窗 ---
      diagnoseDialogVisible: false,
      currentPatient: {}, // 当前正在就诊的病人
      activeTab: 'writeOrder', // 默认激活的标签页

      // Tab: 编写医嘱
      patientOrders: [],
      newOrderContent: '',

      // Tab: 病例编写
      caseFileContent: '',

      surgeryTabLoading: false,
      surgeryForm: {
        surgeryItemId: null, // 选中的手术ID
        surgeryTime: null    // 选中的手术时间
      },
      allSurgeryItems: [],   // 所有手术项目列表 (用于Select)
      patientSurgeries: [],  // 当前病人的手术历史 (用于Table)
      surgeryRules: {
        surgeryItemId: [
          { required: true, message: '请选择一个手术项目', trigger: 'change' }
        ],
        surgeryTime: [
          { required: true, message: '请选择手术时间', trigger: 'change' }
        ]
      }
    };
  },

  // 2. methods 选项
  methods: {
    // 获取主列表数据
    async fetchData() {
      this.loading = true;
      // const query = {
      //   pageNum: this.pagination.pageNum,
      //   pageSize: this.pagination.pageSize,
      //   ...this.searchForm
      // };

      // 对应我们之前设计的 POST /.../list 接口
      let {data:data} = await queryAll();
      console.log(data)
      this.tableData = data.obj
      // this.pagination.total = res.total;
      this.loading = false;
    },

    // 搜索
    handleSearch() {
      this.pagination.pageNum = 1; // 搜索时重置回第一页
      this.fetchData();
    },

    // 重置搜索
    handleReset() {
      this.searchForm.patientName = '';
      this.searchForm.bedNo = '';
      this.handleSearch();
    },

    // 分页：每页条数变化
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.fetchData();
    },

    // 分页：当前页码变化
    handlePageChange(val) {
      this.pagination.pageNum = val;
      this.fetchData();
    },

    // --- 核心操作方法 (对应需求文档) ---

    // 1. 点击"就诊"
    async handleDiagnose(row) {
      this.currentPatient = { ...row };
      this.diagnoseDialogVisible = true;

      // 弹窗打开后，立即加载该病人的历史医嘱
      let {data:data} = await queryByPatientId(row.patientId)
      this.patientOrders = data.obj
      // (也可以在此处加载病例、历史检查等)
    },

    // 2. 弹窗关闭
    handleModalClose() {
      this.currentPatient = {};
      this.activeTab = 'writeOrder'; // 重置Tab
      this.newOrderContent = '';
      this.caseFileContent = '';
      this.patientOrders = [];

      // --- *** 9. 新增: 重置手术Tab *** ---
      this.surgeryForm = { surgeryItemId: null, surgeryTime: null };
      this.allSurgeryItems = [];
      this.patientSurgeries = [];
      if (this.$refs.surgeryFormRef) {
        this.$refs.surgeryFormRef.clearValidate();
      }
    },

    // 3. 提交新医嘱
    async submitNewOrder() {
      if (!this.newOrderContent) {
        ElMessage.warning('医嘱内容不能为空');
        return;
      }
      await submitOrderApi(this.currentPatient.patientId, this.newOrderContent);
      ElMessage.success('新医嘱已提交');
      this.newOrderContent = '';
      // 刷新历史医嘱列表
      this.patientOrders = await fetchOrdersApi(this.currentPatient.patientId);
    },

    // 4. 保存病例
    async submitCaseFile() {
      if (!this.caseFileContent) {
        ElMessage.warning('病例内容不能为空');
        return;
      }
      await submitCaseFileApi(this.currentPatient.patientId, this.caseFileContent);
      ElMessage.success('病例保存成功');
    },

    // 5. 提交出院申请
    submitDischargeApplication() {
      ElMessageBox.confirm(
          `确定要为病人 [${this.currentPatient.patientName}] 提交出院申请吗?`,
          '出院申请确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(async () => {
        // 调用API
        await submitDischargeApi(this.currentPatient.patientId);
        ElMessage.success('出院申请已提交，状态为申请中 ');
        // 刷新主列表 (病人状态可能会改变)
        this.fetchData();
        // 关闭弹窗
        this.diagnoseDialogVisible = false;
      }).catch(() => {
        // 用户点击了取消
      });
    },

    // --- *** 8. 新增: Tab点击事件 (按需加载) *** ---
    async handleTabClick(tab) {
      const tabName = tab.paneName;

      // 按需加载"手术申请"tab的数据，且只加载一次
      if (tabName === 'applySurgery' && this.allSurgeryItems.length === 0) {
        this.surgeryTabLoading = true;
        try {
          // 同时发起两个请求
          const [itemsResponse, historyResponse] = await Promise.all([
            fetchAllSurgeryItemsApi(),
            fetchPatientSurgeriesApi(this.currentPatient.patientId)
          ]);
          this.allSurgeryItems = itemsResponse;
          this.patientSurgeries = historyResponse;
        } catch (error) {
          ElMessage.error('加载手术数据失败');
        } finally {
          this.surgeryTabLoading = false;
        }
      }
      // (您可以为其他Tab添加类似的按需加载逻辑)
    },

    // --- *** 10. 新增: 提交手术申请 *** ---
    submitSurgeryApplication() {
      this.$refs.surgeryFormRef.validate(async (valid) => {
        if (valid) {
          // 验证通过
          ElMessageBox.confirm(
              `确定要为 [${this.currentPatient.patientName}] 申请手术吗?`,
              '手术申请确认',
              { confirmButtonText: '确定', cancelButtonText: '取消', type: 'primary' }
          ).then(async () => {
            try {
              const request = {
                patientId: this.currentPatient.patientId,
                // doctorId 应该由后端从Token解析，这里不传
                surgeryItemId: this.surgeryForm.surgeryItemId,
                surgeryTime: this.surgeryForm.surgeryTime
              };
              // 提交到后端
              const newApplication = await submitSurgeryApi(request);
              ElMessage.success('手术申请提交成功!');

              // 刷新历史列表 (使用模拟数据)
              const selectedItem = this.allSurgeryItems.find(i => i.id === this.surgeryForm.surgeryItemId);
              this.patientSurgeries.push({
                id: newApplication.id,
                surgeryName: selectedItem ? selectedItem.item_name : '新手术',
                surgeryTime: newApplication.surgeryTime,
                status: newApplication.status
              });

              // 重置表单
              this.$refs.surgeryFormRef.resetFields();

            } catch (err) {
              ElMessage.error('申请失败，请重试');
            }
          }).catch(() => {}); // 捕获"取消"操作
        } else {
          // 验证失败
          ElMessage.warning('请检查表单，填写所有必填项');
          return false;
        }
      });
    },

    // --- *** 11. 新增: 格式化手术状态 *** ---
    formatSurgeryStatus(status) {
      // 对应 med_surgery_application.sd_status
      if (status === 0) return '申请中';
      if (status === 1) return '申请成功';
      return '未知';
    },
    //手术申请禁用过去的日期
    disablePastDates(time){
      return time.getTime() < Date.now(); // 禁用过去的日期
    },
    //手术申请禁用过去的小时
    disablePastHours(){
      const arrs = []
      for (let i = 0; i < 24; i++) {
        if (new Date().getHours() <= i) continue;
        arrs.push(i)
      }
      return arrs;
    }
  },

  // 3. created() 钩子
  created() {
    // 页面加载时自动获取第一页数据
    this.fetchData();
  }
};
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}
.el-form {
  border-bottom: 1px solid var(--el-border-color-light);
  padding-bottom: 10px;
  margin-bottom: 20px;
}
/* 确保弹窗内的Tabs内容区有滚动条 */
:deep(.el-tabs__content) {
  max-height: 60vh;
  overflow-y: auto;
}
</style>